package com.lina.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.lina.controller.utils.R;
import com.lina.domain.Dish;
import com.lina.service.IDishService;

import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;

@RestController
@RequestMapping("/dishs")
public class DishController {

//    PathVariable 接收路径变量  RequestBody 接收实体对象
//    新增:POST 删除:Delete 修改:PUT 查询:GET
    @Resource
    private IDishService dishservice;


    @GetMapping
    public R getAll(){
        return new R(true,dishservice.list());
    }

    @PostMapping
    public R save(@RequestBody Dish dish) throws IOException {
//        R r = new R();
//        boolean flag=dishservice.save(book);
//        r.setFlag(flag);
        if (dish.getName().equals("123")) throw  new IOException();
        boolean flag = dishservice.save(dish);
        return new R(flag,flag?"添加成功^_^":"添加失败-_-!");
    }

    @PutMapping
    public R update(@RequestBody Dish dish){
        return new R(dishservice.modify(dish));
    }
    @DeleteMapping("{id}")
    public R delete(@PathVariable Integer id){
        return new R(dishservice.delete(id));
    }
    //http://localhost/dishs/2
    @GetMapping("{id}")
    public R getById(@PathVariable Integer id){
        return new R(true,dishservice.getById(id));
    }


    @GetMapping("/{currentPage}/{pageSize}")
    public R getAll(@PathVariable Integer currentPage,
                    @PathVariable Integer pageSize, Dish dish){
//        System.out.println("参数==>"+name);
//        System.out.println("参数==>"+book);
        //第一种方法
//        IPage page =new Page(currentPage,pageSize);
//        IPage page1 = dishservice.page(page, null);
//        return page1;
        IPage<Dish> page = dishservice.getPage(currentPage, pageSize, dish);
        //如果当前页码值大于总页码值，重新执行查询操作，使用最大页码值当做最大页码值
        if (currentPage >page.getPages()){
            page = dishservice.getPage((int)page.getPages(),pageSize, dish);
        }
        return new R(true,page);
    }




}
